package com.ccys.app.controller;

import cn.hutool.core.util.IdUtil;
import com.ccys.app.service.*;
import com.ccys.common.util.StringUtil;
import com.ccys.common.vo.ResponseResultApp;
import com.ccys.db.dto.app.preConsultDrugAllergies.UpdateBookingDto;
import com.ccys.db.entity.*;
import com.ccys.db.mapper.TblBookingEmergencyContactMapper;
import com.ccys.db.mapper.TblSupplierMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author：XLY
 * @Date：2024/1/25 0025
 */

@RestController
@RequestMapping("/preConsult")
@Api(tags = "Pre-consult Drug Allergies")
public class PreConsultDrugAllergiesController {


    @Resource
    private TblSupplierMapper mapper;

    @Resource
    private BookingSymptomService symptomService;

    @Resource
    private BookingMedicationsService medicationsService;

    @Resource
    private BookingService bookingService;

    @Resource
    private BookingSummaryService summaryService;

    @Resource
    private MemberService memberService;

    @Resource
    private TblBookingEmergencyContactMapper emergencyContactMapper;


    @Resource
    private BookingAllergiesService allergiesService;

    @ApiOperation("Pre-consult Drug Allergies / 1")
    @PostMapping("UpdateBooking")
    @Transactional
    public ResponseResultApp updateBooking(@RequestBody UpdateBookingDto dto) {
        // TODO: 2024/1/25 0025 添加booking_log?
        String booking_id = dto.getBooking_id();

        if (StringUtil.isNotEmpty(booking_id)) {
            //组装实体
            TblBooking booking = new TblBooking();
            TblBookingSummary summary = new TblBookingSummary();

            TblMember member = new TblMember();
            //tbl_booking_medication是问诊时的正在用药
            //tbl_booking_allergies是问诊时的过敏信息,现在整合了过敏药和症状
            //tbl_booking_medication_reactions是问诊时的过敏的症状，已经整合到上面的过敏表
            //tbl_booking_medication不变


            booking.setId(booking_id);
            booking.setConsultationNo(dto.getBooking_code());
            String child_id = dto.getChild_id();
            //child_id字段改成了patient_mem_id
            booking.setPatientMemId(child_id);
            booking.setDoctorId(dto.getDoctor_id());
//        booking.setConsultType(dto.getBooking_type());
            summary.setId(booking_id);
            summary.setG6pd(Boolean.compare(dto.getG6PD(), false));
            summary.setPregnant(Boolean.compare(dto.getPregnant(), false));


            //symptoms
            List<UpdateBookingDto.SymptomVo> symptoms = dto.getSymptoms();
            if (CollectionUtils.isNotEmpty(symptoms)) {
                List<String> symptomIds = mapper.getSymptomIdsByName(symptoms);
                if (CollectionUtils.isNotEmpty(symptomIds)) {
                    List<TblBookingSymptom> collect = symptomIds.stream().map(x -> {
                        TblBookingSymptom symptom = new TblBookingSymptom();
                        symptom.setBookingId(booking_id);
                        symptom.setSymptomId(x);
                        symptom.setId(IdUtil.getSnowflakeNextIdStr());
                        return symptom;
                    }).collect(Collectors.toList());
                    //删除以前的
                    mapper.deleteBookingSymptom(booking_id);
                    //批量插入
                    symptomService.insertAll(collect);
                }
            }

            //medications
            List<UpdateBookingDto.MedicationRequest> medicationRequestList = dto.getMedications();
            if (CollectionUtils.isNotEmpty(medicationRequestList)) {
                List<TblBookingMedications> collect = medicationRequestList.stream().map(x -> {
                    TblBookingMedications medication = new TblBookingMedications();
                    medication.setBookingId(booking_id);
                    //这个usage period需不需要去查询
                    medication.setMedicationUsagePeriodId(x.getUsagePeriod());
                    medication.setAmountOfDosage(x.getAmountOfDosage());
                    medication.setId(IdUtil.getSnowflakeNextIdStr());
                    return medication;
                }).collect(Collectors.toList());
                //删除以前的
                mapper.deleteBookingMedications(booking_id);
                //批量插入
                medicationsService.insertAll(collect);
            }
            List<UpdateBookingDto.AllergiesRequest> allergiesRequestList = dto.getAllergies();
            List<UpdateBookingDto.AllergiesRequest> medication_reactions = dto.getMedication_reactions();
            //tbl_booking_medication_reactions是问诊时的过敏的症状，已经整合到上面的过敏表

            //allergies
            List<TblBookingAllergies> allergiesAndReactions = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(allergiesRequestList)) {
                List<TblBookingAllergies> collect = allergiesRequestList.stream().map(x -> {
                    TblBookingAllergies allergies = new TblBookingAllergies();
                    allergies.setBookingId(booking_id);
                    allergies.setAllergiesName(x.getName());
                    allergies.setId(IdUtil.getSnowflakeNextIdStr());
                    return allergies;
                }).collect(Collectors.toList());
                allergiesAndReactions.addAll(collect);
                //删除以前的，AllergiesName不为null的
                mapper.deleteBookingAllergies(booking_id);
            }

            //medicationReactions
            if (CollectionUtils.isNotEmpty(medication_reactions)) {
                List<TblBookingAllergies> collect = medication_reactions.stream().map(x -> {
                    TblBookingAllergies allergies = new TblBookingAllergies();
                    allergies.setId(IdUtil.getSnowflakeNextIdStr());
                    allergies.setMedicationReactionId(x.getId());
                    allergies.setBookingId(booking_id);
                    return allergies;
                }).collect(Collectors.toList());
                allergiesAndReactions.addAll(collect);
                //删除以前的,medicationReaction不为null的
                mapper.deleteBookingMedicationReactions(booking_id);
            }
            if (CollectionUtils.isNotEmpty(allergiesAndReactions)) {
                allergiesService.insertAll(allergiesAndReactions);
            }
            //card_id 不用管了
            // TODO: 2024/1/25 0025 从card_id开始后面的几个字段
            //emergencyContact
            UpdateBookingDto.EmergencyContact emergency_contact = dto.getEmergency_contact();
            if(Objects.nonNull(emergency_contact)){

                TblBookingEmergencyContact emergencyContact = new TblBookingEmergencyContact();
                BeanUtils.copyProperties(emergency_contact,emergencyContact);
                emergencyContact.setPhoneCountryId(emergency_contact.getPhoneCountry());
                emergencyContact.setBookingId(booking_id);
                //删除之前的
                mapper.deleteBookingEmergencyContact(booking_id);
                //保存
                emergencyContactMapper.insert(emergencyContact);
            }


            booking.setDeeplinkId(dto.getDeeplink_id());
            booking.setMemberAiaCorporateId(dto.getMember_corporate_id());
            UpdateBookingDto.AppointmentVo appointment = dto.getAppointment();
            if (Objects.nonNull(appointment)) {
                booking.setAppointmentType(appointment.getAppointment_type());
                booking.setAppointmentTime(appointment.getAppointment_time());
            }
            booking.setSpecialisationId(dto.getSpecialisation_id());
            String mem_id = dto.getAccount_member_id();
            member.setId(mem_id);
            member.setId(child_id);

            //member
            if (StringUtil.isNotEmpty(mem_id) || StringUtil.isNotEmpty(child_id)) {
                member.setLocationAddress(dto.getLocation_address());
                member.setLocationFloorNumber(dto.getLocation_floor_number());
                member.setLocationPostalCode(dto.getLocation_postal_code());
                member.setLocationCountry(dto.getLocation_country());
                member.setLocationState(dto.getLocation_state());
                member.setLocationLongitude(dto.getLocation_longitude());
                member.setLocationLatitude(dto.getLocation_latitude());

                memberService.insertOrUpdate(member);
            }

            booking.setActiveCode(dto.getActive_code());

            //update
            bookingService.insertOrUpdate(booking);
            summaryService.insertOrUpdate(summary);


        }


        return ResponseResultApp.success();
    }
}
